package dcl.software.filesync.server.auth;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import dcl.software.filesync.server.transfer.TransferUtil;

@Service
public class AuthorizationServiceImpl implements AuthorizationService {
	@Resource
	private UserRepository userRepository;

	public String createAccount(User user) {
		User find = userRepository.findOne(user.getUserName());
		if (find == null) {
			user.setSalt(TransferUtil.getSalt());
			user.setPassword(TransferUtil.getEncodedHash(user.getPassword(), user.getSalt()));
			userRepository.save(user);
		} else
			throw new AuthorizationException("User already exists!");
		return generateToken(user);
	}

	private String generateToken(User user) {
		try {
			return TransferUtil.symetricEncrypt2(user.getUserName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public User getUserFromToken(String token) {
		try {
			String userName = TransferUtil.symetricDecrypt2(token);
			User user = userRepository.findOne(userName);
			return user;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String login(User user) {
		User find = userRepository.findOne(user.getUserName());
		if (find == null)
			throw new IllegalArgumentException("User doesnt exists!");
		if (!TransferUtil.getEncodedHash(user.getPassword(), find.getSalt()).equals(find.getPassword()))
			throw new IllegalArgumentException("User password doesn't match!");
		return generateToken(user);
	}
}
